
#ifndef RTTHREAD_H
#define RTTHREAD_H

#include "RtThreadManager.h"
#include "RtAtomicOperationT.h"

#ifdef RT_WIN32
#define RT_INFINITE INFINITE
#else
#define RT_INFINITE 0xFFFFFFFF 
#endif
#define RT_THREAD_JOIN_TIMEOUT 500 // in milliseconds

class IRtEventQueue;
class IRtTimerQueue;
class IRtReactor;
class CRtEventThread;

class RT_API_EXPORT CRtThread
{
public:
	RT_THREAD_ID GetThreadId();
	CRtThreadManager::TType GetThreadType();
	RT_THREAD_HANDLE GetThreadHandle();
	BOOL IsStopped() const;

	// Create thread.
	// The function won't return until OnThreadInit() returns.
	virtual RtResult Create(
		CRtThreadManager::TType aType, 
		CRtThreadManager::TFlag aFlag = CRtThreadManager::TF_JOINABLE);

	// Stop thread so that let the thread function return.
	virtual RtResult Stop(CRtTimeValue* aTimeout = NULL);

	// Wait until the thread function return.
	RtResult Join(DWORD aMilliseconds = RT_INFINITE);

	// Delete this.
	RtResult Destory(RtResult aReason);

	virtual void OnThreadInit();
	virtual void OnThreadRun() = 0;

	virtual IRtReactor* GetReactor();
	virtual IRtEventQueue* GetEventQueue();
	virtual IRtTimerQueue* GetTimerQueue();

protected:
	CRtThread();
	virtual ~CRtThread();

private:
#ifdef RT_WIN32
	static unsigned WINAPI ThreadProc(void *aPara);
#else
	static void* ThreadProc(void *aPara);
#endif // RT_WIN32

protected:
	RT_THREAD_ID m_Tid;
	RT_THREAD_HANDLE m_Handle;
	CRtThreadManager::TType m_Type;
	CRtThreadManager::TFlag m_Flag;
	BOOL m_stopped;

private:
	CRtEventThread *m_pEvent4Start;
	BOOL m_bRegistered;
	CRtAtomicOperationT<CRtMutexThread> m_NeedDelete;
};

#endif // !RTTHREAD_H
